﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace MyMoviesBrowserLibrary.MyMovies
{
    public class MyMoviesBusiness
    {
        private const string IMDBSearchString = "http://api.themoviedb.org/2.0/Movie.imdbLookup?imdb_id={0}&api_key=4d55ca5fd04590459e2cbd0756c5aad7";
        private const string TitleSearchString = "http://api.themoviedb.org/2.0/Movie.search?title={0}&api_key=4d55ca5fd04590459e2cbd0756c5aad7";
        private const string MovieInfoString = "http://api.themoviedb.org/2.0/Movie.getInfo?id={0}&api_key=4d55ca5fd04590459e2cbd0756c5aad7";

        public static MyMoviesDataContext GetNewMyMoviesDataContext()
        {
            return new MyMoviesDataContext(string.Format(@"Data Source={0}\MYMOVIES;Initial Catalog='My Movies';Persist Security Info=True;User ID=sa;Password=t9AranuHA7", Settings.Default.MyMoviesServerName));
        }

        public static void MarkMovieAsWatched(Title title, bool played)
        {
            MyMoviesDataContext ctx = GetNewMyMoviesDataContext();
            ctx.ExecuteCommand("update tblTitles set bitWatched = @p0 where intId = @p1", played, title.intId);
            //title.Watched = true;
        }

        public List<Movie> SearchByIMDB(string imdb)
        {
            if (string.IsNullOrEmpty(imdb))
                return new List<Movie>();
            XDocument xdoc = XDocument.Load(string.Format(IMDBSearchString, imdb));
            return ParseSearch(ref xdoc);
        }

        public List<Movie> SearchByTitle(string title)
        {
            if (string.IsNullOrEmpty(title))
                return new List<Movie>();
            XDocument xdoc = XDocument.Load(string.Format(TitleSearchString, title));
            return ParseSearch(ref xdoc);            
        }

        private List<Movie> ParseSearch(ref XDocument xdoc)
        {
            List<Movie> movies = new List<Movie>();
            foreach (XElement xMovie in xdoc.Descendants("movie"))
            {
                try
                {
                    Movie movie = new Movie()
                    {
                        ID = xMovie.Element("id").Value,
                        Title = xMovie.Element("title").Value,
                        ShortOverview = xMovie.Element("short_overview") != null ? xMovie.Element("short_overview").Value : ""
                    };
                    XElement poster = xMovie.Elements("poster").Where(p => p.Attribute("size") != null && p.Attribute("size").Value == "thumb").FirstOrDefault();
                    if (poster != null)
                        movie.ThumbnailUrl = poster.Value;
                    poster = xMovie.Elements("poster").Where(p => p.Attribute("size") != null && p.Attribute("size").Value == "mid").FirstOrDefault();
                    if (poster != null)
                        movie.PosterUrl = poster.Value;
                    poster = xMovie.Elements("backdrop").Where(p => p.Attribute("size") != null && p.Attribute("size").Value == "original").FirstOrDefault();
                    if (poster != null)
                        movie.BackgroundUrl = poster.Value;
                    movies.Add(movie);
                }
                catch { }
            }
            return movies;
        }

        public List<Movie> GetMovieInfo(Movie movie, string imageType)
        {
            XDocument xdoc = XDocument.Load(string.Format(MovieInfoString, movie.ID));
            List<Movie> movies = new List<Movie>();

            List<XElement> images;
            if (imageType == "folder")
            {
                images = xdoc.Descendants("poster").ToList();
                foreach (XElement image in images.Where(i => i.Attribute("size") != null && i.Attribute("size").Value == "original"))
                {
                    string temp = image.Value;
                    temp = temp.Replace(System.IO.Path.GetExtension(temp), "");

                    try
                    {
                        Movie tmovie = new Movie() { ID = movie.ID, Title = movie.Title, ShortOverview = movie.ShortOverview };
                        XElement thumb = images.Where(i => i.Attribute("size") != null && i.Attribute("size").Value == "cover" && i.Value.StartsWith(temp)).FirstOrDefault();
                        if (thumb == null)
                            thumb = images.Where(i => i.Attribute("size") != null && i.Attribute("size").Value == "mid" && i.Value.StartsWith(temp)).FirstOrDefault();
                        if (thumb != null)
                            tmovie.ThumbnailUrl = thumb.Value;

                        XElement full = images.Where(i => i.Attribute("size") != null && i.Attribute("size").Value == "mid" && i.Value.StartsWith(temp)).FirstOrDefault();
                        if (full == null)
                            full = images.Where(i => i.Attribute("size") != null && i.Attribute("size").Value == "cover" && i.Value.StartsWith(temp)).FirstOrDefault();
                        if (full != null)
                            tmovie.ImageUrl = full.Value;
                        else
                            continue;

                        movies.Add(tmovie);
                    }
                    catch { }
                }
            }
            else if (imageType == "fanart")
            {
                images = xdoc.Descendants("backdrop").ToList();
                foreach (XElement image in images.Where(i => i.Attribute("size") != null && i.Attribute("size").Value == "original"))
                {
                    string temp = image.Value;
                    temp = temp.Replace(System.IO.Path.GetExtension(temp), "");

                    try
                    {
                        Movie tmovie = new Movie() { ID = movie.ID, Title = movie.Title, ShortOverview = movie.ShortOverview };
                        XElement thumb = images.Where(i => i.Attribute("size") != null && i.Attribute("size").Value == "mid" && i.Value.StartsWith(temp)).FirstOrDefault();
                        if (thumb == null)
                            thumb = images.Where(i => i.Attribute("size") != null && i.Attribute("size").Value == "original" && i.Value.StartsWith(temp)).FirstOrDefault();
                        if (thumb != null)
                            tmovie.ThumbnailUrl = thumb.Value;

                        XElement full = images.Where(i => i.Attribute("size") != null && i.Attribute("size").Value == "original" && i.Value.StartsWith(temp)).FirstOrDefault();
                        if (full != null)
                            tmovie.ImageUrl = full.Value;
                        else
                            continue;

                        movies.Add(tmovie);
                    }
                    catch { }
                }
            }

            return movies;
        }

        public Movie GetDefualtImages(string title, string imdb)
        {
            List<Movie> movies = SearchByIMDB(imdb);
            if (movies.Count == 1)
                return movies[0];
            movies = SearchByTitle(title);
            if (movies.Count == 1)
                return movies[0];
            return null;
        }
    }
}
